package cn.com.godliu.oauth2.controller;

import cn.com.godliu.oauth2.pojo.Account;
import cn.com.godliu.oauth2.pojo.Accountclient;
import cn.com.godliu.oauth2.pojo.OauthClientDetails;
import cn.com.godliu.oauth2.repositorys.AccountClientRepository;
import cn.com.godliu.oauth2.repositorys.AccountRepository;
import cn.com.godliu.oauth2.repositorys.OauthClientDetailsRepository;
import cn.com.godliu.oauth2.responses.ResultOK;
import cn.com.godliu.oauth2.responses.ResultObj;
import cn.com.godliu.oauth2.utils.HttpClientUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import sun.net.www.http.HttpClient;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
public class OauthRegister {

    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private OauthClientDetailsRepository oauthClientDetailsRepository;
    @Autowired
    private AccountClientRepository accountClientRepository;

    private final String salt = "#Godliu#";

    /**
     * 注册用户
     */
    @PostMapping(value = "/register/User", produces = {"application/json;charset=UTF-8"})
    public String registerUse(@RequestBody Account account) {
        if (StringUtils.isEmpty(account.getUsername())) {
            return new Gson().toJson(ResultObj.ResultObj_FAIL(-404, "用户名为空"));
        }
        if (StringUtils.isEmpty(account.getPassword())) {
            return new Gson().toJson(ResultObj.ResultObj_FAIL(-404, "密码为空"));
        }
        account.setUpdatetime(System.currentTimeMillis());
        account.setCreatetime(System.currentTimeMillis());
        ResultObj resultObj;
        try {
            account.setPassword(bCryptPasswordEncoder.encode(account.getPassword()));
            Account account1 = accountRepository.save(account);
            resultObj = new ResultObj();
            resultObj.setCode(1);
            resultObj.setMsg("注册成功");
            resultObj.setObject(account1);
        } catch (Exception e) {
            e.printStackTrace();
            resultObj = ResultObj.ResultObj_FAIL(-1000, e.getMessage());
        }

        return new Gson().toJson(resultObj);
    }


    /**
     * 注册授权码模式的客户端
     *
     * @param accountId
     * @param fallbackCodeUrl
     * @return
     */
    @PostMapping(value = "/register/Authorization", produces = {"application/json;charset=UTF-8"})
    public String registerAuthorization(Long accountId, String fallbackCodeUrl) {
        ResultObj resultObj;
        try {
            Account account1 = accountRepository.getAccountById(accountId);
            if (account1 == null) {
                return new Gson().toJson(ResultObj.ResultObj_FAIL(-404, "用户不存在"));
            }
            OauthClientDetails oauthClientDetails = new OauthClientDetails();
            String account = UUID.randomUUID().toString().replaceAll("-", "");
            oauthClientDetails.setClient_id(account);
            String passwd = UUID.randomUUID().toString().replaceAll("-", "");
            oauthClientDetails.setClient_secret(bCryptPasswordEncoder.encode(passwd + salt));
            oauthClientDetails.setAuthorized_grant_types("authorization_code,refresh_token");
            oauthClientDetails.setAuthorities("ROLE_USER");
            oauthClientDetails.setWeb_server_redirect_uri(fallbackCodeUrl);
            oauthClientDetails.setScope("all");
            oauthClientDetails.setResource_ids("r1");
            oauthClientDetails.setAutoapprove("true");
            oauthClientDetailsRepository.save(oauthClientDetails);

            Accountclient accountclient = new Accountclient();
            accountclient.setAccountid(account1.getId());
            accountclient.setClientid(account);
            accountclient.setSecret(passwd);
            accountclient.setCreatetime(System.currentTimeMillis());
            accountClientRepository.save(accountclient);

            Map<String, String> client = new HashMap<>();
            client.put("appid", account);
            client.put("appsecret", passwd);
            resultObj = new ResultObj(1, "注册成功", client);
        } catch (Exception e) {
            resultObj = new ResultObj(-1000, e.getMessage());
            e.printStackTrace();
        }
        return new Gson().toJson(resultObj);
    }
}
